package wallet

import (
	"bytes"
	"crypto/elliptic"
	"encoding/gob"
	"fmt"
	"io/ioutil"
	"os"
)

type Wallets struct{
	WalletsMap map[string]*Wallet
}

var walletFile="wallets.dat"

func NewWallets()*Wallets{
	w:=&Wallets{make(map[string]*Wallet)}

	if _,err:=os.Stat(walletFile);os.IsNotExist(err){
		return w
	}

	err:=w.LoadFromFile()
	if err!=nil{
		panic(err)
	}

	return w
}

func (w *Wallets)CreateNewWallet(){
	wallet:=NewWallet()
	address:=wallet.GetAddress()

	w.WalletsMap[string(address)]=wallet

	w.SaveToFile()
}

func (w *Wallets)GetAddressList(){
	for address,_:=range w.WalletsMap{
		fmt.Println(address)
	}
}

func (w *Wallets)SaveToFile(){
	var content bytes.Buffer

	gob.Register(elliptic.P256())
	encoder:=gob.NewEncoder(&content)

	err:=encoder.Encode(&w)
	if err!=nil{
		panic(err)
	}

	err=ioutil.WriteFile(walletFile,content.Bytes(),0644)
	if err!=nil{
		panic(err)
	}
}

func (w *Wallets)LoadFromFile()error{

	if _,err:=os.Stat(walletFile);os.IsNotExist(err){
		return nil
	}

	//因为我用的是P521椭圆曲线生成的公私密钥对，所以要用这个来注册
	gob.Register(elliptic.P256())
	fileContent,err:=ioutil.ReadFile(walletFile)
	if err!=nil{
		panic(err)
	}

	var wallets Wallets
	decoder:=gob.NewDecoder(bytes.NewReader(fileContent))
	err=decoder.Decode(&wallets)

	w.WalletsMap=wallets.WalletsMap
	if err!=nil{
		panic(err)
	}

	return nil
}

